package com.huaxin.hxcloud.fragment;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.baidu.mapapi.utils.DistanceUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.HxPunchCardSignBean;
import com.huaxin.common.Entity.HxPunchCardViewBean;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.HxUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.jeek.calendar.widget.calendar.OnCalendarClickListener;
import com.jeek.calendar.widget.calendar.week.WeekCalendarView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author songxf
 * @date 2017/11/23
 * @Desc 考勤---->打卡
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxPunchCardFragment extends BaseFragment
        implements BaiduMap.OnMapLoadedCallback, OnGetPoiSearchResultListener {
    @BindView(R.id.more)
    ImageView        mMore;
    @BindView(R.id.tv_unread)
    TextView         mTvUnread;
    @BindView(R.id.toolbar)
    Toolbar          mToolbar;
    @BindView(R.id.date_tv)
    TextView         mDateTv;
    @BindView(R.id.punch_recyclerview)
    RecyclerView     mPunchRecyclerview;
    @BindView(R.id.punch_state_tv)
    TextView         mPunchStateTv;
    @BindView(R.id.punch_time_tv)
    TextView         mPunchTimeTv;
    @BindView(R.id.punch_lv)
    LinearLayout     mPunchLv;
    @BindView(R.id.scope_tv)
    TextView         mScopeTv;
    @BindView(R.id.mapview)
    MapView          mMapview;
    @BindView(R.id.wcvCalendar)
    WeekCalendarView mWeekCalendarView;

    private HxPunchCardAdapter mPunchCardAdapter;
    private Timer              mTimer;
    private TimerTask          mTask;
    private BaiduMap           mBaiduMap;
    private LocationClient     mLocClient;
    boolean isFirstLoc = true; // 是否首次定位
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float          mCurrentAccracy;
    private MyLocationData locData;
    private int mCurrentDirection = 0;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationConfiguration              mConfiguration;
    private BitmapDescriptor                     mCurrentMarker;
    private Double lastX = 0.0;
    private PoiSearch mPoiSearch;
    private LatLng    mMlatLng;
    private int       mConfigRadius;
    private int                                         searchType    = 0;  // 搜索的类型，在显示时区分
    private List<HxPunchCardViewBean.DataBean.SignBean> mSignBeanList = new ArrayList<>();
    private double mConfigLat;
    private double mConfigLng;
    private boolean isShowDialog = false;//是否显示dialog
    private Dialog mDialog;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_punch_card;
    }

    @Override
    protected void onResumeView() {
        super.onResumeView();

        ((BaseActivity) getActivity()).setSupportActionBar(mToolbar);
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mToolbar.setTitle("考勤打卡");
        initMapSearch();
        initPunchRecycler();
        onTimer();

        mDateTv.setText(HxUtils.getYearMonthDay());
        initMap();
        initLocation();
        initCalendar();
        mDialog = DialogUtil.getWaitDialog(getContext(), "加载中...");
    }

    private void initCalendar() {
        mWeekCalendarView.setOnCalendarClickListener(new OnCalendarClickListener() {
            @Override
            public void onClickDate(int year, int month, int day) {
                String today = year + "-" + (month + 1) + "-" + day;
                requestTodayData(today, LOAD_SUCCESS, !isShowDialog);
            }

            @Override
            public void onPageChange(int year, int month, int day) {

            }
        });
    }

    @Override
    public void onResume() {
        mMapview.onResume();

        super.onResume();
    }

    private void initPunchRecycler() {
        mPunchRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        mPunchRecyclerview.setHasFixedSize(true);
        mPunchCardAdapter = new HxPunchCardAdapter(getContext());
        mPunchRecyclerview.setAdapter(mPunchCardAdapter);
        mPunchCardAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.update_time_tv:
                        switch (mSignBeanList.size()) {
                            case 1:
                            case 2:
                                setPunchCardSign(1, mCurrentLon, mCurrentLat);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }


    /**
     * 检索功能
     */
    private void poiSearchOption(String address, double lat, double lng, int radius) {
        mMlatLng = new LatLng(lat, lng);
        PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption()
                .keyword(address)
                .sortType(PoiSortType.distance_from_near_to_far)
                .location(mMlatLng)
                .radius(radius).pageNum(0);
        mPoiSearch.searchNearby(nearbySearchOption);
    }


    /**
     * 初始化搜索模块，注册搜索事件监听
     */
    private void initMapSearch() {
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        searchType = 1;
    }

    @Override
    protected void requestData() {
        requestTodayData(HxUtils.getYearMonthDay(), LOADING, isShowDialog);
    }

    private void requestTodayData(final String today, final int viewState, final boolean isShowDialog) {
        updateLoadStatus(viewState);
        isShowDialog(isShowDialog);
        mPunchCardAdapter.getData().clear();
        Call<HxPunchCardViewBean> beanCall = HxTransmitRequestHelper.getRequestApi().getAttendance(today);
        autoClose(beanCall);
        beanCall.enqueue(new Callback<HxPunchCardViewBean>() {
            @Override
            public void onResponse(Call<HxPunchCardViewBean> call, Response<HxPunchCardViewBean> response) {
                HxPunchCardViewBean.DataBean dataBean = response.body().getData();
                cancleDialog();
                if (response.isSuccessful()) {
                    updateLoadStatus(LOAD_SUCCESS);
                    List<HxPunchCardViewBean.DataBean.SignBean> signBeanList = dataBean.getSign();
                    setPunchState(signBeanList);
                    String mAddress = dataBean.getCenter().getAddress();
                    if (signBeanList != null) {
                        mSignBeanList.addAll(signBeanList);
                        mPunchCardAdapter.setSelectDay(today);
                    }
                    mPunchCardAdapter.setNewData(mSignBeanList);
                    mConfigLat = dataBean.getCenter().getLat();
                    mConfigLng = dataBean.getCenter().getLng();
                    mConfigRadius = dataBean.getCenter().getRadius();
                    String scopeDes;
                    if (isScopePunchCard(mCurrentLat, mCurrentLon, mConfigLat, mConfigLng, mConfigRadius)) {
                        scopeDes = "已进入考勤范围:";
                    } else {
                        scopeDes = "还未进入考勤范围:";
                    }
                    mScopeTv.setText((scopeDes + mAddress));
                    poiSearchOption(mAddress, mConfigLat, mConfigLng, mConfigRadius);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<HxPunchCardViewBean> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
                cancleDialog();
            }
        });
    }

    /**
     * 是否显示dialog
     *
     * @param isShow
     */
    private void isShowDialog(boolean isShow) {
        if (isShow) {
            mDialog.show();
        }
    }

    /**
     * 隐藏dialog
     */
    private void cancleDialog() {
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
    }


    /**
     * 初始定位
     */
    private void initLocation() {
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //定位初始化
        mLocClient = new LocationClient(getContext());
        mLocClient.registerLocationListener(new MyLocationListenner());
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mConfiguration = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfigeration(mConfiguration);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    private void initMap() {
        // 隐藏logo
        View child = mMapview.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        mBaiduMap = mMapview.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setBuildingsEnabled(false);
    }

    @OnClick({R.id.punch_lv, R.id.scope_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.punch_lv://考勤打卡  打卡类型：0.签到；1.签退；
                if (mSignBeanList.size() == 0) {
                    setPunchCardSign(0, mCurrentLon, mCurrentLat);
                } else if (mSignBeanList.size() == 1) {
                    setPunchCardSign(1, mCurrentLon, mCurrentLat);
                }
                break;
            case R.id.scope_tv:
                break;
        }
    }


    /**
     * 是否在正常打卡
     * 计算当前定位经纬度和打卡配置经纬度距离
     * 来判断是否在正常打卡范围内
     *
     * @param currentLat
     * @param currentLng
     * @param configLat
     * @param configlng
     * @param configRadius
     * @return true 正常打卡 false 外勤打卡
     */
    private boolean isScopePunchCard(double currentLat, double currentLng, double configLat, double configlng, int configRadius) {
        //当前坐标
        LatLng currentPoint = new LatLng(currentLat, currentLng);
        //打卡坐标
        LatLng configPoint = new LatLng(configLat, configlng);
        double distance = DistanceUtil.getDistance(currentPoint, configPoint);
        if (distance < configRadius) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据的大小判断上班还是下班
     *
     * @param signBeanList
     */
    private void setPunchState(List<HxPunchCardViewBean.DataBean.SignBean> signBeanList) {
        String punchCardState = null;
        if (signBeanList != null) {
            switch (signBeanList.size()) {
                case 0:
                    punchCardState = "上班打卡";
                    mPunchLv.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    punchCardState = "下班打卡";
                    mPunchLv.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    punchCardState = "下班打卡";
                    mPunchLv.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        } else {
            punchCardState = "上班打卡";
        }
        mPunchStateTv.setText(punchCardState);
    }

    /**
     * 签到打卡
     */
    private void setPunchCardSign(int signtype, double currentLon, double currentLat) {
        mDialog.show();
       /* if (isScopePunchCard(currentLat, currentLon, mConfigLat, mConfigLng, mConfigRadius)) {
            ToastUtil.showToast("正常打卡");
        } else {
            ToastUtil.showToast("外勤打卡");
        }*/

        Call<HxPunchCardSignBean> signBeanCall = HxTransmitRequestHelper.getRequestApi().getAttendanceSign(signtype, currentLon, currentLat);
        autoClose(signBeanCall);
        signBeanCall.enqueue(new Callback<HxPunchCardSignBean>() {
            @Override
            public void onResponse(Call<HxPunchCardSignBean> call, Response<HxPunchCardSignBean> response) {
                mDialog.cancel();
                HxPunchCardSignBean mSignBean = response.body();
                if (response.isSuccessful()) {
                    mDialog.cancel();
                    mSignBeanList.clear();
                    if (mSignBean.getData().getSign().size() == 2) {
                        mPunchLv.setVisibility(View.GONE);
                    } else {
                        mPunchLv.setVisibility(View.VISIBLE);
                    }
                    for (HxPunchCardSignBean.DataBean.SignBean signBean : mSignBean.getData().getSign()) {
                        HxPunchCardViewBean.DataBean.SignBean signViewBeans = new HxPunchCardViewBean.DataBean.SignBean();
                        signViewBeans.setTime(signBean.getTime());
                        signViewBeans.setType(signBean.getType());
                        signViewBeans.setAddress(signBean.getAddress());
                        mSignBeanList.add(signViewBeans);
                    }
                    setPunchState(mSignBeanList);
                    mPunchCardAdapter.setNewData(mSignBeanList);
                }
                ToastUtil.showToast(mSignBean.getMsg());
            }

            @Override
            public void onFailure(Call<HxPunchCardSignBean> call, Throwable t) {
                ToastUtil.showToast(t.getMessage());
                mDialog.cancel();
            }
        });
    }

    /**
     * 获取POI搜索结果，包括searchInCity，searchNearby，searchInBound返回的搜索结果
     *
     * @param result
     */
    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            ToastUtil.showToast("未找到结果");
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaiduMap.clear();
            switch (searchType) {
                case 1:
                    showNearbyArea(mMlatLng, mConfigRadius);
                    break;
                default:
                    break;
            }


            return;
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            ToastUtil.showToast(strInfo);
        }
    }

    /**
     * 对周边检索的范围进行绘制
     *
     * @param center
     * @param radius
     */
    public void showNearbyArea(LatLng center, int radius) {
        BitmapDescriptor centerBitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.config_address);
        MarkerOptions ooMarker = new MarkerOptions().position(center).icon(centerBitmap);
        mBaiduMap.addOverlay(ooMarker);

        OverlayOptions ooCircle = new CircleOptions().fillColor(getContext().getResources().getColor(R.color.color_6accecfb))
                .center(center).stroke(new Stroke(5, getContext().getResources().getColor(R.color.color_00A0E9)))
                .radius(radius);
        mBaiduMap.addOverlay(ooCircle);
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastUtil.showToast("抱歉，未找到结果");
        } else {
            ToastUtil.showToast(result.getName() + ": " + result.getAddress());
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }


    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(16.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }
    }


    /**
     * 计时器1s刷新一次
     */
    private void onTimer() {
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    mPunchTimeTv.setText(HxUtils.getCurrentTime());
                }
                super.handleMessage(msg);
            }
        };
        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        mTimer.schedule(mTask, 100, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null && mTask != null) {
            mTimer.cancel();
        }
        if (mPoiSearch != null) {
            mPoiSearch.destroy();
        }
    }

    @Override
    public void onMapLoaded() {

    }
}
